

import 'package:xim/http/apis/message/message_model.dart';
import 'package:xim/http/apis/secret/secret_api.dart';
import 'package:xim/http/http.dart';

class MessageApi {

  /// 查询最新的消息，没有返回空
  static Future<ChatMessageModel?> queryLatestMessage(int sessionId) async {
    var resp = await dio.postResult(
        "/store/message/query/message/latest",
        queryParameters: {"sessionId": sessionId}
    );
    return ChatMessageModel.fromJson(resp.data);
  }

  /// 查询会话消息
  /// limit 消息条数
  /// anchorMessageId 锚点消息Id， -1 表示最新消息Id
  static Future<List<ChatMessageModel>> queryMessageList(int sessionId,{int limit=20, int anchorMessageId=-1}) async {
    var resp = await dio.postResult(
        "/store/message/query/anchor",
        data: {"sessionId": sessionId, "limit": limit, "anchor": anchorMessageId}
    );
    var messageList = resp.data as List;
    return messageList.map((e) => ChatMessageModel.fromJson(e)).toList();
  }

  /// 查询未读消息条数(当前用户)
  static Future<int> queryUnReadMessageCount(int sessionId) async {
    var resp = await dio.postResult(
        "/store/session/query/unReadMessage/count",
        queryParameters: {
          "sessionId": sessionId
        }
    );
    return resp.data as int;
  }


  /// 将消息标记为已读状态
  static Future<void> makeHasRead(int messgaeId){
    dio.postResult("/store/message/read/remark", queryParameters: {"messageId": messgaeId});
    return Future.value();
  }

  /// 获取消息信息
  static Future<ChatMessageModel> queryMessageById(int messageId) async {
    var respData = await dio.postResult("/store/message/query/message/id", queryParameters: {"messageId": messageId});
    return ChatMessageModel.fromJson(respData.data);
  }

  /// 获取会话历史消息
  Future<List<ChatMessageModel>> requestSessionChatMessage(int sessionId) async{
    var result = await dio.postResult("/store/message/query/session/chatMessage", data: {"sessionId":sessionId});
    var data = result.data as List<dynamic>;
    return data.map((e) => ChatMessageModel.fromJson(e)).toList();
  }

  /// 发送消息（http方式）
  static Future<bool> sendChatMessage(ChatMessageStoreModel message) async {
    var result = await dio.postResult("/push/send/chatMessage", data: message.toJson());
    return result.isSuccess();
  }

}
